from django import forms
from .models import JoinInformation

class JoinInformationForm(forms.ModelForm):
    class Meta:
        model = JoinInformation
        fields = ['email', 'name', 'phone', 'address', 'order_details', 'notes']
        widgets = {
            'notes': forms.Textarea(attrs={'rows': 3}),
        }
        # 明确指定哪些字段是必需的
        required_fields = ['name', 'address', 'order_details']

    def clean_phone(self):
        phone = self.cleaned_data.get('phone')
        if phone and not (phone.isdigit() and len(phone) in [11]):
            raise forms.ValidationError('请输入有效的手机号')
        return phone

    def clean(self):
        cleaned_data = super().clean()
        email = cleaned_data.get('email')
        phone = cleaned_data.get('phone')
        name = cleaned_data.get('name')
        address = cleaned_data.get('address')
        order_details = cleaned_data.get('order_details')

        # 验证邮箱和电话至少填一个
        if not email and not phone:
            self.add_error(None, '邮箱与手机号至少填写一个')

        # 验证除备注外其他字段必填
        if not name:
            self.add_error('name', '姓名为必填项')
        if not address:
            self.add_error('address', '通讯地址为必填项')
        if not order_details:
            self.add_error('order_details', '订购信息为必填项')

        return cleaned_data